package com.dsg.service.oil.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.common.constants.DsgStatusConstant;
import com.dsg.dao.oil.DsgOilAccountMapper;
import com.dsg.entity.oil.DsgOilAccount;
import com.dsg.service.base.impl.BaseServiceImpl;
import com.dsg.service.oil.IDsgOilAccountService;
import com.dsg.util.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("dsgOilAccountService")
public class DsgOilAccountServiceImpl extends BaseServiceImpl<DsgOilAccountMapper, DsgOilAccount> implements IDsgOilAccountService {

    @Autowired
    private DsgOilAccountMapper dsgOilAccountMapper;

    @Override
    public IPage<DsgOilAccount> selectByList(Page<DsgOilAccount> page, DsgOilAccount dsgOilAccount) {
        return page.setRecords(dsgOilAccountMapper.selectByList(page, dsgOilAccount));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDefault(String id) {
        DsgOilAccount dsgOilAccount = getById(id);
        if (dsgOilAccount != null) {
            QueryWrapper<DsgOilAccount> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PID", dsgOilAccount.getPid());
            List<DsgOilAccount> dsgOilAccountList = dsgOilAccountMapper.selectList(queryWrapper);
            dsgOilAccountList.forEach(I -> {
                if (id.equals(I.getOid())) {
                    I.setIsDefault(DsgStatusConstant.IS_DEFAULT_ONE);
                } else {
                    I.setIsDefault(DsgStatusConstant.IS_DEFAULT_ZERO);
                }
            });
            updateBatchById(dsgOilAccountList);
            return true;
        } else {
            throw new RRException("賬戶信息不存在！");
        }
    }
}
